package xyz.hlh.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import xyz.hlh.annotition.LoginUser;
import xyz.hlh.annotition.LoginValidator;
import xyz.hlh.common.BaseResult;
import xyz.hlh.common.Constant;
import xyz.hlh.common.LoginUserThread;
import xyz.hlh.entity.User;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author HLH
 * @email 17703595860@163.com
 * @date : Created in  2021/8/1 下午4:53
 */
@RestController
@RequestMapping("/user")
@LoginValidator // 拦截当前类中的所有方法
public class UserController implements BaseResult {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /** 模拟的用户列表 */
    private static final List<User> PRE_USER_LIST = new ArrayList<User>() {
        private static final long serialVersionUID = -7220237466804914720L;
        {
            add(new User(1, "zhangsan", "123", true));
            add(new User(2, "lisi", "456", true));
            add(new User(3, "wangwu", "789", true));
        }
    };

    @PostMapping("/login")
    @LoginValidator(validated = false) // 放行登录接口
    public ResponseEntity<?> login(@RequestBody User user) {
        // 获取参数
        String username = user.getUsername();
        String password = user.getPassword();
        if (StringUtils.isAnyBlank(username, password)) {
            return internalError("用户名或者密码错误");
        }

        // 登陆判断
        List<User> userList = PRE_USER_LIST.stream()
                .filter(tempUser -> StringUtils.equals(username, tempUser.getUsername()))
                .collect(Collectors.toList());
        if (userList.size() != 1) {
            return internalError("用户不存在");
        }
        User loginUser = userList.get(0);
        if (!StringUtils.equals(password, loginUser.getPassword())) {
            return internalError("密码错误");
        }
        if (!loginUser.getEnable()) {
            return internalError("账户已经被锁定");
        }
        // 生成token，把登陆信息存入redis，有效期30分钟
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(Constant.REDIS_USER_PREFIX + token, loginUser, 30, TimeUnit.MINUTES);
        return success(token);
    }

    @GetMapping
    public ResponseEntity<?> findAllUser() {
        System.out.println(LoginUserThread.get());
        return success(PRE_USER_LIST);
    }

    @GetMapping("/test")
    public String test(@LoginUser User user) {
        System.out.println(user);
        return "测试编码";
    }

}
